<template>
  <div class="app-container">

    <div class="box ph-30">
      <div class="panel">
        <div class="panel-header">
          <h3 class="panel-title">选择参赛项目</h3>
        </div>
        <div class="panel-body">

          <div class="text-right mb20">
            <el-button type="success" @click="chooseProject">选择项目</el-button>
          </div>
          <el-table border :data="tableData" style="width: 100%">
            <el-table-column type="index" label="序号" width="50"/>
            <el-table-column label="运动员" min-width="120">
              <template #default="scope">
                <div class="td-flex">
                  <img width="50" :src="scope.row.cptPersonInfo.picUrl">
                  <div class="info">
                    {{ scope.row.cptPersonInfo.realName }}({{ scope.row.cptPersonInfo.sexStr }})
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="证件号" min-width="150">
              <template #default="scope">
                {{ scope.row.cptPersonInfo.idcTypeStr }}
                <p class="m0">{{ scope.row.cptPersonInfo.idcCode }}</p>
              </template>
            </el-table-column>
            <el-table-column label="项目/组别/级别" min-width="150">
              <template #default="scope">

                {{ scope.row.cptProjectName }}&ensp;{{ scope.row.cptGroupName }}{{ scope.row.cptLevelName }}
              </template>
            </el-table-column>
            <el-table-column v-for="(p,index) in extraPersonInfoMapList" :key="index" :label="p.key">
              <template #default="scope">
                <el-link type="success" v-if="p.type=='2'" :herf="scope.row.extraPersonInfoMapList[index].value">
                  文件
                </el-link>
                <img v-else-if="p.type=='3'" style="width: 50px;" :src="scope.row.extraPersonInfoMapList[index].value">
                <span v-else>{{ scope.row.extraPersonInfoMapList[index].value }}</span>
              </template>
            </el-table-column>
            <el-table-column label="国籍" prop="cptPersonInfo.countryName"/>
            <el-table-column label="民族" prop="cptPersonInfo.nation"/>
            <el-table-column label="联系电话" min-width="110" prop="cptPersonInfo.phone"/>
            <el-table-column label="出生日期" min-width="100" prop="cptPersonInfo.birth"/>

            <el-table-column label="教练" v-if="coachOrLeaderFlag==1">
              <template #default="scope">
                <div class="hand" @click="chooseCoach">{{ scope.row.coachNames }}</div>
              </template>
            </el-table-column>
            <el-table-column label="领队" v-if="coachOrLeaderFlag==1">
              <template #default="scope">
                <div class="hand" @click="chooseCoach">{{ scope.row.leaderNames }}</div>
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" fixed="right" width="100">
              <template #default="scope">
                <!--                <el-button type="text">编辑</el-button>-->
                <el-button type="text" @click="removeThis(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>


        </div>
        <div class="panel-footer text-center">
          <el-button type="success" plain round @click="goPrev()">上一步</el-button>
          <el-button type="success" round @click="submitForm()">下一步</el-button>
        </div>
      </div>
    </div>

    <dialogProjectList ref="dialogProjectListRef" @submitForm="getMySignInfo"/>

    <el-dialog v-model="showResult" :close-on-click-modal="false" :show-close="false">
      <el-result
          icon="success"
          title="报名成功"
      >
        <template #extra>
          <el-button type="primary" @click="downloadVoucher">下载凭证</el-button>
          <el-button type="primary" @click="goMySign">查看报项</el-button>
        </template>
      </el-result>

    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { getCurrentInstance, onMounted } from '@vue/runtime-core'
import * as match from '@/api/match/pc'
import dialogProjectList from './components/sportsmanList'
import { useRoute, useRouter } from 'vue-router'

const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()
import { ElMessage, ElMessageBox } from 'element-plus'

let signInfoType
const data = reactive({
  tableData: [],
  extraPersonInfoMapList: [],
  matchId: '',
  showResult: false
})
const { tableData, extraPersonInfoMapList, matchId, showResult } = toRefs(data)

let chargeFlag
const coachOrLeaderFlag = ref('')
let noPhotoCanSign
onMounted(() => {
  matchId.value = route.query.matchId
  getMySignInfo()
  getMatch()
  getMyself()
})

function getMatch() {
  match.getMatchById({
    id: matchId.value
  }).then(res => {
    chargeFlag = res.data.chargeFlag
    coachOrLeaderFlag.value = res.data.coachOrLeaderFlag
    noPhotoCanSign = res.data.noPhotoCanSign
  })
}

function getMySignInfo() {
  match.getMySignInfo({ cptId: matchId.value, groupId: '' }).then(res => {
    console.log(res.data)
    signInfoType = res.data.type
    if (!res.data.signInfo) {
      tableData.value = []
      return
    }
    tableData.value = res.data.signInfo
    extraPersonInfoMapList.value = res.data.signInfo[0]?.extraPersonInfoMapList
  })
}

let personId
const getMyself = () => {
  match.getMyPersonInfo().then(res => {
    personId = res.data.id
  })
}

function submitForm() {
  if (signInfoType == '1') {
    ElMessageBox.confirm('已报项，前往我的报项', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      router.push({ name: 'myMatch' })
    })
    return
  }
  if (signInfoType == '2') {
    match.recoverMySign({ cptId: matchId.value }).then(res => {
      if (res.msg.indexOf('Exception:') > -1) {
        const msg = res.msg.slice(10)
        ElMessageBox.confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log('用户点击确定')
        })
        return
      } else {
        afterRecover()
      }
    })
  } else {
    afterRecover()
  }
}

function afterRecover() {
  if (tableData.value.length == 0) {
    ElMessage.error('请至少选择一个项目')
    return
  }
  // 判断是否收费
  if (chargeFlag == '0') {
    var obj = {
      cptId: matchId.value,
      groupId: ''
    }
    match.commitSign(obj).then(res => {
      console.log(res.data)
      showResult.value = true
    })
  } else {
    // 生成账单
    router.push({
      name: 'expenseDetails',
      query: {
        personId: personId
      }
    })
  }
}

function goMySign() {
  router.push({
    name: 'myMatch'
  })
}

function goPrev() {
  router.go(-1)
}

function chooseProject() {
  if (signInfoType == '2') {
    match.recoverMySign({ cptId: matchId.value }).then(res => {
      if (res.msg.indexOf('Exception:') > -1) {
        const msg = res.msg.slice(10)
        ElMessageBox.confirm(msg).then(() => {
          console.log('用户点击确定')
        })
        return
      }
      getMySignInfo()
    })
  }
  match.getMyPersonInfo().then(res => {
    console.log(res.data)
    const params = {
      title: '选择项目',
      matchId: matchId.value,
      groupId: 0,
      personal: res.data,
      signType: 0,
      noPhotoCanSign: noPhotoCanSign,
      coachOrLeaderFlag: coachOrLeaderFlag.value
    }
    proxy.$refs['dialogProjectListRef'].open(params)
  })
}

function removeThis(p) {
  ElMessageBox.confirm('确定移除这条报项吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    match.deleteSign(p.id).then(res => {
      // 重新获取已报名信息
      ElMessage.success('已移除该报项')
      getMySignInfo()
    })
  })
}

function chooseCoach() {
  // goPrev()
}

function downloadVoucher() {
  proxy.download(
    `/pdf/getPayedOrderPdf/${matchId.value}/0`, {}, '报项凭证.pdf'
  )
}
</script>

<style scoped lang="scss">
.app-container {
  padding: 0;
  background: #F5F7F9;
}

.panel-footer .el-button--success {
  background: linear-gradient(270deg, #39DBA7, #38EF7D);
  border: none;
  padding: 0 40px;
  font-size: 16px;
}

.panel-footer .el-button--success.is-plain {
  background: #fff;
  border: 1px solid #2ED981;
  color: #2ED981;
}

.chooseForm {
  :deep(.el-form-item__content) {
    background: rgba(245, 247, 249, 0.38);
    padding: 20px 40px 10px;
  }

  .el-checkbox {
    height: auto;
  }

  :deep(.el-checkbox__input) {
    position: absolute;
    right: 0;
    top: 0;
  }

  .name {
    text-align: center;
  }
}

.td-flex {
  display: flex;
  align-items: center;

  .info {
    padding-left: 10px;
    font-size: 14px;
  }
}

</style>
